package com.yc.starter.upload;

import com.yc.starter.upload.config.UploadMapper;
import com.yc.starter.upload.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * @author navy
 * @company 源辰信息
 * @date 2024/9/10
 * @email haijunzhou@hnit.edu.cn
 */
@Configuration
@ConditionalOnClass(DispatcherServlet.class)
@ConditionalOnProperty(prefix = "upload", name = "enable", havingValue="true")
@ComponentScan("com.yc.starter.upload")
@Slf4j
public class UploadConfig implements WebMvcConfigurer {

    @Autowired
    UploadProperties properties;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        for (UploadMapper mapper : properties.getMappers()) {
            String webPath = mapper.getWebPath() + "**";
            String diskPath = "file:" + mapper.getDiskPath();
            File file = new File(mapper.getDiskPath());
            if(file.exists() == false){
                if (file.mkdirs() == false) {
                    throw new RuntimeException("创建上传目录失败!");
                }
            }
            log.debug(webPath + " => " + diskPath);
            registry.addResourceHandler(webPath)
                    .addResourceLocations(diskPath);
        }
    }
}
